package com.corecmd.tcloud.tcimserver.imclient.handler;

import com.corecmd.tcloud.tcimcommon.im.common.PacketCodeC;
import com.corecmd.tcloud.tcimcommon.im.domain.LoginRequestPacket;
import com.corecmd.tcloud.tcimcommon.im.domain.MessageRequestPacket;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * @author : TianShaoJiao
 * @date : 2021/2/20
 * @description :
 **/
@Slf4j
public class ClientHandler extends SimpleChannelInboundHandler<String> {
    private String userId;
    private String userName;
    public ClientHandler(String userId,String userName){
        this.userId = userId;
        this.userName = userName;
    }
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(new Date() + ": 客户端开始登录");
        Channel channel = ctx.channel();
        // 创建登录对象
        LoginRequestPacket loginRequestPacket = new LoginRequestPacket();
        loginRequestPacket.setUserId(userId);
        loginRequestPacket.setUsername(userName);
        loginRequestPacket.setPlatform("pc");
        // 编码
        ByteBuf buffer = new PacketCodeC().encode(loginRequestPacket);
        // 写数据
        channel.writeAndFlush(buffer);
    }
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String o) throws Exception {
        // 创建登录对象
        MessageRequestPacket messageRequestPacket = new MessageRequestPacket();
        messageRequestPacket.setVersion("1".getBytes()[0]);
        // 编码
        ByteBuf buffer = new PacketCodeC().encode(messageRequestPacket);
        // 写数据
        channelHandlerContext.channel().writeAndFlush(buffer);
        channelHandlerContext.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Channel channel = ctx.channel();
        if(channel.isActive()){
            ctx.close();
        }
    }
}
